package com.kaifamiao.base.Demo20210926;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author lucien-ma
 * @date 2021/9/26
 * @apiNote
 */
public class Demo02 {

    public static void main(String[] args) {
        recover("E:/test/出师表.txt");
    }

    /**
     * 恢复文件顺序
     * @param file
     */
    public static void recover(File file) {
        List<String> list = new ArrayList<>();
        InputStream in = null;
        BufferedReader bufferedReader = null;
        OutputStream out = null;
        BufferedWriter bufferedWriter = null;
        try {
            in = new FileInputStream(file);
            bufferedReader = new BufferedReader(new InputStreamReader(in));
            String line = null;
            // 将信息保存到集合中
            while ((line = bufferedReader.readLine()) != null) {
                list.add(line);
            }
            // 对集合进行排序
            Collections.sort(list);
            // 再一行行写入进去
            out = new FileOutputStream(file);
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(out));
            // 将排序好的信息放进去
            for (String s : list) {
                bufferedWriter.write(s);
                // 换行
                bufferedWriter.newLine();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedWriter.close();
                out.close();
                bufferedReader.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void recover(String filePath) {
        recover(new File(filePath));
    }
}
